<template>
	<div class="make_an_appointment" v-loading="saveUploading.status" :element-loading-text="saveUploading.txt" v-loading.fullscreen.lock="saveUploading.full">
		<div class="teach_h classIndex_h clear">
			<em @click="resetForm()">预约直播</em>
			<strong><i>></i>预约</strong>
		</div>
		<!--  -->
		<div class="publishFrom">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<div class="make_time" :class="{ 'live-timer': $store.state.isSchool }">
					<el-form-item label="直播时间" label-width="100px" prop="liveTime">
						<el-select @change="liveDayTime" v-model="ruleForm.liveTime" placeholder="请选择" v-if='!$store.state.isSchool'>
							<el-option label="自定义时间" :value="1"></el-option>
							<el-option label="节次" :value="2"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label-width="0" prop="date_time">
						<el-date-picker v-model="ruleForm.date_time" type="date" @change="dateChange" value-format="yyyy-MM-dd" :picker-options='pickerOptions' placeholder="直播时间" style="width: 100%">
						</el-date-picker>
					</el-form-item>
					<el-form-item label-width="0" prop="Livesection" v-if='dayTime'>
						<el-select filterable @change="timeSectionChange" v-model="ruleForm.Livesection" placeholder="请选择">
							<el-option v-for="(item, index) in nodeTime" :label="`第${item.section}节  ${item.start_time} - ${item.end_time}`" :value="item.section" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<!--  -->
					<el-form-item label-width="0" class="Livesection" v-else>
						<el-col :span="11">
							<el-form-item prop="start_time">
								<el-time-picker v-if='0' v-model="ruleForm.start_time" type="date" value-format="HH:mm" format="HH:mm" placeholder="开始时间" style="width: 100%">
								</el-time-picker>
								<el-time-select placeholder="开始时间" v-model="ruleForm.start_time" :picker-options="{
								     start: '00:00',
								     step: '00:05',
								     end: '23:59',
								     minTime:init_start_time,
								      maxTime: ruleForm.end_time
								   }">
								</el-time-select>
							</el-form-item>
						</el-col>
						<el-col class="line" :span="2">-</el-col>
						<el-col :span="11">
							<el-form-item prop="end_time">
								<el-time-picker v-if='0' v-model="ruleForm.end_time" type="date" value-format="HH:mm" format="HH:mm" :picker-options='{
								 		minTime: ruleForm.start_time
								 	}' placeholder="结束时间" style="width: 100%">
								</el-time-picker>
								<el-time-select placeholder="结束时间" v-model="ruleForm.end_time" :picker-options="{
								    start: '00:00',
								    step: '00:05',
								    end: '23:59',
								    minTime: ruleForm.start_time
								  }">
								</el-time-select>
							</el-form-item>
						</el-col>
					</el-form-item>
				</div>
				<el-form-item label="直播名称" prop="name">
					<el-input v-model="ruleForm.name" placeholder="最多可输入30个字" maxlength="30"></el-input>
				</el-form-item>
				<ul>
					<li class="publishFrom_seleck">
						<el-form-item label="直播设备" prop="recorder_id">
							<el-select filterable v-model="ruleForm.recorder_id" placeholder="请选择">
								<el-option v-for="(item, index) in recorderData" :label="item.name" :value="item.id" :key="index"></el-option>
							</el-select>
						</el-form-item>
					</li>
					<!--  -->
					<template v-if='!$store.state.isSchool'>
						<li class="publishFrom_seleck">
							<el-form-item label="学段" prop="study_section_id">
								<el-select filterable v-model="ruleForm.study_section_id" @change="setRange($event, 'section')"  placeholder="请选择">
									<el-option v-for="(item, index) in orgLevel2" :label="item.name" :value="item.id" :key="index"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="年级" prop="grade_id">
								<el-select filterable v-model="ruleForm.grade_id" @change="setRange($event, 'grade')"placeholder="请选择">
									<el-option v-for="(item, index) in orgLevel3" :label="item.name" :value="item.id" :key="index"></el-option>
								</el-select>
							</el-form-item>
						</li>
						<!--  -->
						<li class="publishFrom_seleck">
							<el-form-item label="科目" prop="subject_id">
								<el-select filterable v-model="ruleForm.subject_id" placeholder="请选择">
									<el-option v-for="(item, index) in orgSubject" :label="item.name" :value="item.id" :key="index"></el-option>
								</el-select>
							</el-form-item>
						</li>
						<!--  -->
						<li class="publishFrom_seleck" prop="class_id">
							<el-form-item label="通知班级">
								<el-checkbox-group v-model="ruleForm.class_id">
									<el-checkbox v-for="(item, index) in noticeClass" :label="item.id" :value="item.id" name="type" :key="index">{{item.rename}}</el-checkbox>
								</el-checkbox-group>
							</el-form-item>
						</li>
					</template>
				</ul>
				<el-form-item label="是否录制" prop="is_record">
					<el-radio-group v-model="ruleForm.is_record">
						<el-radio :label="1">是</el-radio>
						<el-radio :label="0">否</el-radio>
					</el-radio-group>
				</el-form-item>
				<template v-if="1">
					<div class="livePassword clear">
						<el-form-item label="直播密码" prop="isPassword">
							<el-radio-group v-model="ruleForm.isPassword" @change="setPassword">
								<el-radio :label="1">开启</el-radio>
								<el-radio :label="0">关闭</el-radio>
							</el-radio-group>
							<span class="cipherTips">（开启密码后，前台用户需要输入正确的直播密码才能观看直播）</span>
						</el-form-item>
						<div class="liveCipher" v-if="ruleForm.isPassword == 1">
							<el-form-item prop="password">
								<el-input type="password" v-model="ruleForm.password" placeholder="设置直播观看密码" maxlength="6"></el-input>
							</el-form-item>
							<el-form-item prop="isCipher">
								<el-input type="password" v-model="ruleForm.isCipher" placeholder="确认直播观看密码" maxlength="6"></el-input>
							</el-form-item>
						</div>
					</div>
				</template>
				<template v-if="showAI">
					<div class="is_ai clear" v-if="ruleForm.is_record === 1">
						<el-form-item label="AI教学分析" prop="is_ai">
							<el-radio-group v-model="ruleForm.is_ai">
								<el-radio :label="1">是</el-radio>
								<el-radio :label="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="上课班级" prop="ai_class_id" v-if="ruleForm.is_ai == 1">
							<el-select filterable v-model="ruleForm.ai_class_id " placeholder="请选择">
								<el-option v-for="(item, index) in noticeClass" :label="item.rename" :value="item.id" :key="index"></el-option>
							</el-select>
						</el-form-item>
					</div>
				</template>
				<!-- <template v-if='!$store.state.isSchool'>
					<el-form-item label="观看权限" class="jurisdiction">
						<el-radio-group v-model="ruleForm.jurisdiction" @change="changeJurisdiction">
							<el-radio label="0">不限制</el-radio>
							<el-radio label="1">按角色限制</el-radio>
							<template v-if='!$store.state.isSchool'>
								<el-radio label="2">按年级限制</el-radio>
								<el-radio label="3">按班级限制</el-radio>
							</template>
						</el-radio-group>
					</el-form-item>
					<template v-if="ruleForm.jurisdiction == 1">
						<el-form-item label-width="100px" prop="roleArray" class="roleArray">
							<el-scrollbar>
								<el-checkbox-group v-model="ruleForm.roleArray">
									<template v-for="item of allRoleList">
										<el-checkbox :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
									</template>
								</el-checkbox-group>
							</el-scrollbar>
						</el-form-item>
					</template>
					<template v-if="ruleForm.jurisdiction == 2">
						<el-form-item label-width="100px" prop='gradeArray' class="gradeArray">
							<el-scrollbar>
								<el-checkbox-group v-model="ruleForm.gradeArray">
									<template v-for="item of allGradeList">
										<el-checkbox :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
									</template>
								</el-checkbox-group>
							</el-scrollbar>
						</el-form-item>
					</template>
					<template v-if="ruleForm.jurisdiction == 3">
						<el-form-item label-width="100px" prop="calssArray" class="calssArray">
							<div class="calssArray-wp">
								<el-tree class="allClass" :data="allClassList" id='tree' show-checkbox ref="tree" node-key="id" default-expand-all highlight-current :props="defaultProps" @check="handleCheckChange">
								</el-tree>
								<div class="calssArray-r">
									<h3>限制观看班级</h3>
									<el-scrollbar>
										<ul>
											<li v-for="(item, index) of classCheck" :key="index">
												<h3>{{item.name}}</h3>
												<div>
													<template v-for="(tag, index2) of item.children">
														<span :key="index2" @click="deldeteCalss(index, index2, tag.id)">{{tag.name}} <i class="el-icon-close"></i></span>
													</template>
												</div>
											</li>
										</ul>
									</el-scrollbar>
								</div>
							</div>
							<el-checkbox-group v-model="ruleForm.calssArray">
								<template v-for="item of allClassList">
									<template v-for="item2 of item.children">
										<template v-for="item3 of item2.children">
											<el-checkbox :label="item3.id">{{item3.name}}</el-checkbox>
										</template>
									</template>
								</template>
							</el-checkbox-group>
						</el-form-item>
					</template>
				</template> -->
				<el-form-item label="封面图片" prop="imageUrl2">
					<div class="publishFrom_ box">
						<img v-if="previewImgURL" :src="previewImgURL" class="avatar">
						<div class="publishFrom_b" v-else>
							<i class="ipm image_up"></i>
							<p>点击上传图片</p>
							<p>支持jpg/png/jpeg格式</p>
						</div>
						<uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText" @files-submitted="fileSubmit" @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail" class="uploader-broadcast uploader-live">
							<uploader-unsupport></uploader-unsupport>
							<uploader-btn :directory="false" :attrs="attrs" :single="true">
								<i class="ipm video_up" @click="clearFilet"></i>
							</uploader-btn>
							<uploader-list></uploader-list>
						</uploader>
					</div>
				</el-form-item>
				<el-form-item label="直播简介" prop="profile">
					<el-input type="textarea" :rows="6" resize="none" v-model.tirm="ruleForm.profile" maxlength="200" placeholder="请输入直播简介,不超200字"></el-input>
					<span class="numberWord"><i>{{ ruleForm.profile.length }}</i>/200</span>
				</el-form-item>
				<el-form-item class="buttonCSS">
					<el-button @click="resetForm('ruleForm')" type="primary" plain>取消</el-button>
					<el-button type="primary" @click="submitForm('ruleForm')" v-preventReClick>保存</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!--  -->
		<el-dialog title="图片设置" :visible.sync="tailorViews" width="1000px" custom-class="Tailoring" :close-on-click-modal="false">
			<div class="tailoring">
				<div class="tailoring_cropper">
					<vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :fixedBox="option.fixedBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" :centerBox="option.centerBox" :high="option.high" :infoTrue="option.infoTrue" :enlarge="option.enlarge">
					</vueCropper>
				</div>
				<div class="buttonCSS cropper_btn">
					<el-button type="primary" @click="clearFilet(1)" plain>取消</el-button>
					<el-button type="primary" @click="finish('base64')">确定</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>
<script>
export default {
	name: '',
	data() {
		return {
			teachClass: [],
			pickerOptions: {
				disabledDate: (time) => {
					return time.getTime() < Date.now() - 8.64e7;
				}
			},
			init_start_time: timestampToTime().substr(11, 5),
			ruleForm: {
				name: '', //视频名称
				recorder_id: parseInt(this.$route.query.id) ? parseInt(this.$route.query.id) : '', //直播设备
				study_section_id: '', //学段
				grade_id: '', //年级
				subject_id: '', //科目
				profile: '', //视频简介
				imageUrl2: undefined,
				class_id: [], //通知班级
				// date_time: timestampToTime().substr(0,10), //日历
				date_time: undefined, //日历
				liveTime: 1, //直播时间
				Livesection: undefined,
				start_time: undefined, //开始时间
				end_time: undefined, //结束时间
				is_record: 0,
				type: 0,
				is_ai: 0,
				ai_class_id: undefined,
				isPassword: 0,
				password: undefined,
				isCipher: undefined,
				jurisdiction: '0',
				gradeArray: [],
				roleArray: [],
				calssArray: []
			},

			props: { multiple: true },
			rules: {
				name: [
					{ required: true, message: '请输入直播名称', trigger: 'blur' },
					{ validator: this.validateName, trigger: 'blur' }
				],
				recorder_id: [
					{ required: true, message: '请选择直播设备', trigger: 'change' }
				],
				/*study_section_id: [
					{ required: true, message: '请选择学段', trigger: 'change' }
				],
				grade_id: [
					{ required: true, message: '请选择年级', trigger: 'change' }
				],
				subject_id: [
					{ required: true, message: '请选择科目	', trigger: 'change' }
				],*/
				start_time: [
					{ required: true, message: '请选择开始时间	', trigger: 'change' }
				],
				end_time: [
					{ required: true, message: '请选择结束时间	', trigger: 'change' }
				],
				date_time: [
					{ required: true, message: '请选择日期', trigger: 'change' }
				],
				liveTime: [
					{ required: true, message: '请选择时间	', trigger: 'change' }
				],
				Livesection: [
					{ required: true, message: '请选择时间	', trigger: 'change' }
				],
				ai_class_id: [
					{ required: true, message: '上课班级	', trigger: 'change' }
				],
				password: [
					{ validator: this.validatePassword, trigger: 'blur' },
					{ min: 6, max: 6, message: '请输入6位数字密码', trigger: 'blur' }
				],
				isCipher: [
					{ min: 6, max: 6, validator: this.validateisPassword, trigger: 'change' },
				],
				gradeArray: [
					{ required: true, message: '请选择年级	', trigger: 'change' }
				],
				roleArray: [
					{ required: true, message: '请选择角色	', trigger: 'change' }
				],
				calssArray: [
					{ required: true, message: '请选择班级	', trigger: 'change' }
				],
			},
			recorderData: [],
			dayTime: false,
			nodeTime: [],
			orgLevel2: this.$g.orgLevel2, //学段
			orgLevel3: [], //年级
			orgSubject: [], //科目
			noticeClass: [], //班级通知

			statusText: {
				success: '上传成功',
				error: '上传出错',
				uploading: '正在上传...',
				paused: '暂停',
				waiting: '等待上传'
			},
			selectFileOrNot: false, //是否选中文件
			uploadOrNot: false, //是否已经上传
			uploadInfo: {
				file_name: '',
				file_path: '',
				file_size: 0
			},
			attrs: {
				accept: ['image/*']
			},
			uploadOptions: {
				target: this.BASE_URL + '/api/resource/res_upload',
				testChunks: false,
				headers: { Authorization: `Bearer ` + this.$g.access_token },
			},
			selectFileShow: true, //是否显示选择文件按钮
			uploadRetryTimes: 100, //文件最大重传次数
			previewImgURL: '',
			tailorViews: false,
			modelSrc: '',
			modelView: '',
			previews: '',

			option: {
				img: '',
				size: 1,
				full: false, //full
				outputType: 'png', //输出图片格式
				canMove: true, //能否拖动图片
				fixedBox: true, //截图框固定大小
				original: true, //否显示原始宽高
				canMoveBox: true, //能否拖动截图框
				autoCrop: true, //autoCrop 是否自动生成截图框
				// 只有自动截图开启 宽度高度才生效
				autoCropWidth: 290,
				autoCropHeight: 160,
				centerBox: false, //截图框是否限制在图片里
				high: true //high //是否根据dpr生成适合屏幕的高清图片
			},
			fileNumber: 0,
			uploadNumber: 0,
			saveUploading: {
				status: false,
				txt: "正在保存...",
				full: false
			},

			allGradeList: [],
			/*年级数组*/
			allRoleList: [],
			/*角色数组*/
			allClassList: [],
			/*班级数组*/
			classCheck: [],
			checkArray: [],
			idList: [], // 默认level为2、3 id
			defaultProps: {
				children: 'children',
				label: 'name'
			},
			showAI: false
		}
	},
	created() {
		let timer = setTimeout(()=>{this.orgLevel2 = this.$g.orgLevel2; clearTimeout(timer);}, 1000);
	},
	mounted() {
		this.$nextTick(() => {
			this.getTimeset()

			this.getNoticeClass()
			this.getRecorder();
			this.getshowAI()
			this.allRole();
			this.allGrade();
			this.allClass();
		})
	},
	watch: {
		'ruleForm.type': {
			handler(b) {
				if (parseInt(b) === 1) {
					this.ruleForm.date_time = timestampToTime().substr(0, 10);
					this.ruleForm.start_time = timestampToTime().substr(11, 8);
					this.ruleForm.end_time = '';
				} else {
					this.ruleForm.date_time = timestampToTime().substr(0, 10);
					this.ruleForm.start_time = '';
					this.ruleForm.end_time = '';
				}
			}
		},
		'ruleForm.is_record'(newval, val) {
			if (newval === 0) {
				this.ruleForm.is_ai = 0
				this.ruleForm.ai_class_id = ''
			}
		}
	},
	methods: {
		/**
		 *  日期改变时重置时间可选范围
		 */
		dateChange(data) {
			if (data == timestampToTime().substr(0, 10)) {
				this.init_start_time = timestampToTime().substr(11, 5);
			} else {
				this.init_start_time = '';
			}
		},
		getshowAI() {
			let success = (res => {
				this.showAI  = res.data == 'yes' ? true : false
			})
			let fail = (res => {
				this.showAI = false
			})
			this.$ajax({
				url: 'api/app/check_ai',
				method: 'get',
				params: {},
				func: { success: success, fail: fail }
			})
		},
		/**
		 * 删除限制观看的班级
		 * @DateTime 2019-08-08T10:18:41+0800
		 * @param    {[strong]}     i 数组的索引
		 * @param    {[strong]}      j 数组的 children 索引
		 * @return   {[type]}                   [description]
		 */
		deldeteCalss(i, j, id) {
			this.defaHalf = this.defaHalf.filter(item => {
				return item != id
			})

			let temp = [];
			this.allClassList.forEach(item => [
				item.children && item.children.forEach(item2 => {
					item2.children && item2.children.forEach(item3 => {
						if (this.defaHalf.includes(item3.id)) {
							temp.push({
								id: item3.id,
								name: item3.name
							})
						}
					})
				})
			])

			this.$refs.tree.setCheckedNodes(temp);
			this.handleCheckChange();
		},
		/**
		 * 对象、树目前的选中状态对象
		 * @DateTime 2019-07-24T09:37:48+0800
		 * @param    {[Strong]}   data    
		 * @param    {[Array]}    checked 四个属性来读取选中的id,对象结构
		 */
		handleCheckChange(data, checked) {
			let _half = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
			this.defaHalf = _half;

			this.ruleForm.calssArray = _half.filter(items => {
				if (!this.idList.includes(items)) return items;
			})

			let _classCheck = [];
			let _temp1 = [];
			this.classCheck = [];

			this.allClassList.forEach(item1 => {
				item1.children && item1.children.forEach(item2 => {
					item2.children && item2.children.forEach(item3 => {
						if (this.ruleForm.calssArray.includes(item3.id)) {
							_classCheck.push({
								id: item3.id,
								pid: item3.pid,
								name: item3.name
							})

							if (!_temp1.includes(item3.pid)) {
								_temp1.push(item3.pid);

								this.classCheck.push({
									name: this.getGradeName(item3.pid),
									pid: item3.pid,
									children: []
								})
							}
						}
					})
				})
			})

			_classCheck.forEach(item => {
				let inx = _temp1.indexOf(item.pid);

				this.classCheck[inx].children.push({
					id: item.id,
					name: item.name
				})
			})
		},
		/**
		 * 获取年级名字
		 */
		getGradeName(id) {
			let name = '';

			this.allClassList.forEach(item1 => {
				item1.children && item1.children.forEach(item2 => {
					if (item2.id === id) {
						name = item2.name;
					}
				})
			})

			return name;
		},
		/**
		 * 观看权限
		 * @param {String} val 切换标识
		 */
		changeJurisdiction(val) {
			this.ruleForm.gradeArray = [];
			this.ruleForm.roleArray = [];
			this.ruleForm.calssArray = [];
			this.classCheck = [];
		},
		/**
		 * 获取所有班级
		 * @DateTime 2019-08-05T10:49:16+0800
		 * @return   {[type]}                 [description]
		 */
		allClass() {

			let success = (res => {
				this.allClassList = res.data[0].children;

				for (var i = 0; i < this.allClassList.length; i++) {
					if (this.allClassList[i].children !== 0) {

						for (let j = 0; j < this.allClassList[i].children.length; j++) {
							let item = this.allClassList[i].children[j];
							item.disabled = item.children.length > 0 ? false : true;
						}
					}
				}

				// 获取 level 为 2、3 的值
				this.allClassList.forEach(item => {
					this.idList.push(item.id);
					item.children && item.children.forEach(item2 => {
						this.idList.push(item2.id);
					})
				})
			});



			let params = { data_type: 'manage_tree', status: '1,2' }
			if (this.$store.state.isCheckLevel) {
				params = {}
				this.$ajax.get('api/newlevel/levelorg_list', { params: params, func: { success: success } })
			} else {
				this.$ajax.get('api/org/org', { params: params, func: { success: success } })
			}

		},
		/**
		 * 获取所有角色
		 * @DateTime 2019-08-05T10:42:45+0800
		 * @return   {[type]}                 [description]
		 */
		allRole() {
			let success = (res => {
				this.allRoleList = res.data;
			});

			let params ={type: 1 }
			if (this.$store.state.isCheckLevel) {
				this.$ajax.get('api/user/user_allow_control', { params: params, func: { success: success } })
			} else {
				this.$ajax.get('api/role/get_small_role', { params: params, func: { success: success } })
			}
		},
		/*
		    获取所有年级
		 */
		allGrade() {
			let success = (res => {
				this.allGradeList = res.data;
			});

			let params = {}
			if (this.$store.state.isCheckLevel) {
				params.level = 3
				params.direction = 'balance'
				this.$ajax.get('api/newlevel/platform_org', { params: params, func: { success: success } })
			} else {
				this.$ajax.get('api/org/all_grade', { params: params, func: { success: success } })
			}
		},
		/*
		 *
		 */
		setPassword(val) {
			if (val == 0) {
				this.ruleForm.password = ''
			}
		},
		/*
		 *	验证输入框不能输入中文，由6位字母數字组成
		 */
		isChineseChar(str) {
			var reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
			return reg.test(str);
		},
		/*
		 * 校验邀请码输入内容是否为空 
		 */
		validatePassword(rule, value, callback) {

			if (is_empty(value)) {
				return callback(new Error('邀请码不能为空'));
			} else if (this.isChineseChar(value)) {
				return callback(new Error('不能否含有中文，由6位字母數字组成，区分大小写'));

			} else {
				callback()
			}

		},
		/*
		 * 校验邀请码输入内容是否为空
		 */
		validateisPassword(rule, value, callback) {

			if (is_empty(value)) {
				return callback(new Error('密码不能为空'));
			} else if (this.isChineseChar(value)) {
				return callback(new Error('不能否含有中文，由字母數字组成，区分大小写'));

			} else if (value !== this.ruleForm.password) {
				return callback(new Error('两次密码不一样'));
			} else {
				callback()
			}

		},
		/*校验邀请码输入内容是否为空 */
		validateName(rule, value, callback) {
			let reg = /^[\w\u4e00-\u9fa5]+$/gi;

			if (!reg.test(value)) {
				callback(new Error('直播名称只能是中文、数字、字母!'));
			} else {
				callback();
			}

		},
		//清空上传控件列表的数据
		clearFilet(val) {
			if (val === 1) {
				this.tailorViews = false
				this.modelView = ''
				this.$refs.uploader.uploader.fileList = []
				this.$refs.uploader.uploader.files = []
				this.$refs.uploader.fileList = []
			} else {
				this.modelView = ''
				this.$refs.uploader.uploader.fileList = []
				this.$refs.uploader.uploader.files = []
				this.$refs.uploader.fileList = []
			}
		},
		//图片裁剪后替换原图片
		finish(type) {
			if (type === 'blob') {
				this.$refs.cropper.getCropBlob((data) => {
					this.tailorViews = false
				})
			} else {
				this.$refs.cropper.getCropData((data) => {
					this.modelView = this.dataURLtoFile(data, this.$refs.uploader.uploader.fileList[0].name)
					this.$refs.uploader.uploader.fileList[0].file = this.modelView
					this.$refs.uploader.uploader.files[0].file = this.modelView
					this.$refs.uploader.uploader.fileList[0].size = this.modelView.size
					this.$refs.uploader.uploader.files[0].size = this.modelView.size

					this.$refs.uploader.uploader.fileList[0].uniqueIdentifier = this.modelView.size + "-" + this.$refs.uploader.uploader.fileList[0].name;
					this.$refs.uploader.uploader.fileList[0].chunks[0].endByte = this.modelView.size;

					this.modelSrc = data
					this.previewImgURL = data
					this.tailorViews = false
				})
			}
		},
		//将base64转换为文件
		dataURLtoFile(dataurl, filename) {
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new File([u8arr], filename, { type: mime });

		},
		saveLive() {
			let array = [...this.ruleForm.gradeArray, ...this.ruleForm.roleArray, ...this.ruleForm.calssArray];
			let params = {
				name: this.ruleForm.name,
				study_section_id: this.ruleForm.study_section_id,
				grade_id: this.ruleForm.grade_id,
				subject_id: this.ruleForm.subject_id,
				class_id: this.ruleForm.class_id,
				recorder_id: this.ruleForm.recorder_id,
				create_id: this.$g.user_id,
				start_time: this.ruleForm.date_time + ' ' + this.ruleForm.start_time,
				end_time: this.ruleForm.date_time + ' ' + this.ruleForm.end_time,
				picture: this.ruleForm.picture,
				authority: this.ruleForm.authority,
				is_mobile: this.ruleForm.is_mobile,
				is_record: this.ruleForm.is_record,
				record_status: this.ruleForm.record_status,
				profile: this.ruleForm.profile,
				comment: this.ruleForm.comment,
				status: this.ruleForm.status,
				is_record: this.ruleForm.is_record,
				is_ai: this.ruleForm.is_ai,
				ai_class_id: this.ruleForm.ai_class_id,
				password: this.ruleForm.password,
				limit_type: this.ruleForm.jurisdiction,
				limit_id: array
			}

			let success = (data => {
				this.$message.success(data.msg);
				setTimeout(() => {
					this.$router.push({ path: '/teach/live/listlive' })
				}, 1000);
			});

			const fail = (res => {
				/** 2019-6-10 失败返回提示是一个数组 */
				let text = '';
				this.selectFileOrNot = false;
				this.$refs.uploader.fileList = [];
				this.$refs.uploader.files = [];
				res.msg.forEach(item => {
					text += item + ';  ';
				})

				this.$message.error(text)
			})

			this.$ajax.post('api/live/live', params, { func: { success: success, fail: fail } })
		},
		//直播时间--自定义时间--节次
		getTimeset() {
			let success = (res => {
				let data = res.data;
				this.nodeTime = data;
			});
			this.$ajax({
				url: "/api/school/timeset",
				method: 'get',
				params: {},
				func: {
					success: success
				}
			})
		},
		//自定义时间
		liveDayTime() {
			if (parseInt(this.ruleForm.liveTime) === 1) {
				this.dayTime = true;
				this.ruleForm.Livesection = '';
			} else {
				this.ruleForm.startTime = '';
				this.ruleForm.endTime = '';
				this.dayTime = false
			}
			this.ruleForm.start_time = ''
			this.ruleForm.end_time = ''
			this.ruleForm.liveTime == 1 ? this.dayTime = false : this.dayTime = true
		},
		setRange(val, type) {

			switch (type) {
				case 'section':
					this.ruleForm.grade_id = '';
					this.ruleForm.subject_id = ''

					this.orgLevel3 = []
					this.orgSubject = []
					this.getOrgLevel3()
					break;
				case 'grade':

					this.ruleForm.subject_id = ''

					this.orgSubject = []
					this.getSubject()
					break;
			}

		},
		//获取年级
		getOrgLevel3() {
			let success = res => {
				let data = res.data;
				this.orgLevel3 = data;
			};
			let params = {
				level: 3,
				pid: this.ruleForm.study_section_id,
				direction: 'balance',
			}

			if (this.$store.state.isCheckLevel) {
				this.$ajax.get('api/newlevel/platform_org', { params: params, func: { success: success } })
			} else {
				this.$ajax.get('api/org/org', { params: params, func: { success: success } })
			}
		},
		//科目
		getSubject() {
			let success = res => {
				let data = res.data;
				this.orgSubject = data;
			};
			let params = {
				type: 2,
				org_id: this.ruleForm.grade_id,
				status: 1,
			}

			if (this.$store.state.isCheckLevel) {
				this.$ajax.get('api/newlevel/platform_subject', { params: params, func: { success: success } })
			} else {
				this.$ajax.get('api/cate/subject', { params: params, func: { success: success } })
			}
		},
		//通知班级
		getAITeaching() {
			let success = (res => {
				let data = res.data;
				this.teachClass = data;
			});
			this.$ajax({
				url: 'api/org/org',
				method: 'get',
				params: {
					level: 4,
					direction: 'balance',
					pid: this.ruleForm.grade_id,
					status: 1,
				},
				func: {
					success: success
				}
			})
		},
		//通知班级
		getNoticeClass() {
			let success = (res => {
				let data = res.data;
				this.noticeClass = data;
			});
			this.$ajax({
				url: 'api/org/class_userid',
				method: 'get',
				params: {
					style: 1,
					data_type: 0,
					user_id: this.$g.user_id,
				},
				func: {
					success: success
				}
			})
		},
		timeSectionChange(value) {
			this.ruleForm.start_time = this.nodeTime[value - 1].start_time;
			this.ruleForm.end_time = this.nodeTime[value - 1].end_time;
		},

		//表单验证
		submitForm(formName) {

			this.$refs[formName].validate((valid) => {
				document.querySelector('.is-error') && this.scrollToTop('.is-error')
				if (valid) {

					this.fileNumber = this.$refs.uploader.fileList.length
					if (this.fileNumber > 0) {
						this.fileUpload();
					} else {
						this.saveLive();
					}

				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		resetForm(formName) {
			this.$router.back(-1)
		},
		getRecorder() {
			this.recorderData = []
			let success = (data => {

				for (let i = 0; i < data.data.length; i++) {
					if (data.data[i].status == 1) {
						this.recorderData.push(data.data[i])
					}
				}
			})
			this.$ajax.get('api/recorder/recorder_list', { params: {}, func: { success: success } })

		},
		//上传成功的事件  
		fileSuccess(rootFile, file, message, chunk) {
			var mess = JSON.parse(message);
			mess = handleResponseData(mess)
			if (parseInt(mess.data.status) === 1) {
				this.uploadOrNot = true;
				this.uploadInfo.file_size = file.size;
				this.uploadInfo.file_name = mess.data.file_name;
				this.uploadInfo.file_path = mess.data.file_path;
				this.uploadInfo.post_fix = mess.data.post_fix;
				this.ruleForm.picture = this.uploadInfo.file_path;
				this.saveLive();
			} else if (mess.status === 'fail') {
				this.$message.error(mess.msg + ' ' + file.name)
				this.$refs.uploader.uploader.cancel()
			}
		},
		fileFail(rootFile, file, message, chunk) {
			var mess = eval('(' + message + ')');
			if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
				let callbcak = (data => {
					this.uploadRetryTimes--;
					this.$refs.uploader.uploader.retry(file);
				})
				this.get_access_token(callbcak);
			} else {
				this.$message.error(mess.msg);
			}
		},
		fileSubmit(files, fileList, event) {

			var arrImg = ['image/jpg', 'image/jpeg', 'image/bmp', 'image/gif', 'image/png']
			this.ruleForm.select_or_not = '1';
			this.selectFileOrNot = true;
			this.selectFileShow = false;

			if (this.$refs.uploader.uploader.fileList.length >= 2) {
				this.$refs.uploader.uploader.fileList.splice(0, 1)
				this.$refs.uploader.uploader.files.splice(0, 1)
			}

			for (var i = 0; i < fileList.length; i++) {
				var ext = fileList[i].name.split('.').pop();
				var file_type = fileList[i].fileType;

				if (!arrImg.includes(file_type)) {

					this.$message.warning("只支持jpg, jpeg, gif, png, bmp格式图片")
					this.$refs.uploader.uploader.removeFile(fileList[i]);
					return

				} else if (fileList[i].size === 0) {

					this.$refs.uploader.uploader.cancel();
					this.$message.error('上传文件大小不能小于0');
					this.selectFileShow = true;
				} else if (fileList[i].size > 10480000) {
					this.$message.warning('只允许上传10M以内的文件');
					this.$refs.uploader.uploader.removeFile(fileList[i]);
				} else {
					fileList[i].fileType = 'image/png'
					fileList[i].name = fileList[i].name.replace(/\.\w+$/, '.png')
					fileList[i].relativePath = fileList[i].relativePath.replace(/\.\w+$/, '.png')
					this.option.img = window.URL.createObjectURL(fileList[i].file)
					this.tailorViews = true;
				}

			}
		},
		fileRemoved(file) {
			this.previewImgURL = '';
			this.ruleForm.select_or_not = '';
			this.selectFileOrNot = false;
			this.selectFileShow = true;
		},
		fileUpload() {
			this.$refs.uploader.uploader.resume();
		},
	}
}
</script>
<style lang="css">
.cropper_btn {
	background: #fff;
}
.tailoring {
	height: 500px;
}
.tailoring_cropper {
	height: 100%;
}
.tailoring_cropper>div {
	height: 100%;
}
.vue-cropper {
	position: relative;
	width: 100%;
	height: 500px;
	box-sizing: border-box;
	user-select: none;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	direction: ltr;
	touch-action: none;
	text-align: left;
	background-image: url("");
}
.cropper-box,
.cropper-box-canvas,
.cropper-drag-box,
.cropper-crop-box,
.cropper-face {
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	user-select: none;
}
.cropper-box-canvas img {
	position: relative;
	text-align: left;
	user-select: none;
	transform: none;
	max-width: none;
	max-height: none;
}
.cropper-box {
	overflow: hidden;

}
.cropper-move {
	cursor: move;
}
.cropper-crop {
	cursor: crosshair;
}
.cropper-modal {
	background: rgba(0, 0, 0, 0.5);
}
.cropper-crop-box {
	/*border: 2px solid #39f;*/
}
.cropper-view-box {
	display: block;
	overflow: hidden;
	width: 100%;
	height: 100%;
	outline: 1px solid #39f;
	outline-color: rgba(51, 153, 255, 0.75);
	user-select: none;
}
.cropper-view-box img {
	user-select: none;
	text-align: left;
	max-width: none;
	max-height: none;
}
.cropper-face {
	top: 0;
	left: 0;
	background-color: #fff;
	opacity: 0.1;
}
.crop-info {
	position: absolute;
	left: 0px;
	min-width: 65px;
	text-align: center;
	color: white;
	line-height: 20px;
	background-color: rgba(0, 0, 0, 0.8);
	font-size: 12px;
}
.crop-line {
	position: absolute;
	display: block;
	width: 100%;
	height: 100%;
	opacity: 0.1;
}
.line-w {
	top: -3px;
	left: 0;
	height: 5px;
	cursor: n-resize;
}
.line-a {
	top: 0;
	left: -3px;
	width: 5px;
	cursor: w-resize;
}
.line-s {
	bottom: -3px;
	left: 0;
	height: 5px;
	cursor: s-resize;
}
.line-d {
	top: 0;
	right: -3px;
	width: 5px;
	cursor: e-resize;
}
.crop-point {
	position: absolute;
	width: 8px;
	height: 8px;
	opacity: 0.75;
	background-color: #39f;
	border-radius: 100%;
}
.point1 {
	top: -4px;
	left: -4px;
	cursor: nw-resize;
}
.point2 {
	top: -5px;
	left: 50%;
	margin-left: -3px;
	cursor: n-resize;
}
.point3 {
	top: -4px;
	right: -4px;
	cursor: ne-resize;
}
.point4 {
	top: 50%;
	left: -4px;
	margin-top: -3px;
	cursor: w-resize;
}
.point5 {
	top: 50%;
	right: -4px;
	margin-top: -3px;
	cursor: e-resize;
}
.point6 {
	bottom: -5px;
	left: -4px;
	cursor: sw-resize;
}
.point7 {
	bottom: -5px;
	left: 50%;
	margin-left: -3px;
	cursor: s-resize;
}
.point8 {
	bottom: -5px;
	right: -4px;
	cursor: se-resize;
}
</style>